<template>
  <ele-page flex-table>
    <ComHeader :title="`出库通知单详情[${info?.order_sn}]`" @back="goBack" />
    <ele-bottom-bar v-if="active === '1'" :teleported="true">
      <template #extra>
        <template v-if="command">
          <el-button type="info" @click="back()">返回</el-button>
          <el-button type="primary" :loading="loading" @click="save()">保存</el-button>
        </template>
        <template v-else>
          <el-button v-if="info.is_cd === 1" type="" plain @click="onCommand('CD')">取消订单</el-button>
          <el-button v-if="info.start_jh === 1" type="primary" plain @click="onCommand('START')">开始拣货</el-button>
          <el-button v-if="info.is_jh === 1" type="primary" plain @click="onCommand('JH')">拣货</el-button>
          <el-button v-if="info.is_yh === 1" type="primary" plain @click="onCommand('YH')">验货</el-button>
          <el-button v-if="info.is_db === 1" type="primary" plain @click="onCommand('DB')">打包</el-button>
          <el-button v-if="info.is_fh === 1" type="primary" @click="onCommand('FH')">发货</el-button>
          <el-button v-if="info.is_jd === 1" type="primary" @click="onCommand('JD')">结单</el-button>
        </template>
        <el-button type="" @click="openPrint">打印单据</el-button>
      </template>
    </ele-bottom-bar>

    <ele-card flex-table bordered :header-style="{ padding: '0 16px' }">
      <template #header>
        <ele-tabs
          v-model="active"
          :items="[
            { name: '1', label: '基础信息' },
            { name: '2', label: '拣货列表' },
            { name: '3', label: '验货列表' },
            { name: '4', label: '打包列表' },
            { name: '5', label: '发货列表' },
            { name: '6', label: '操作列表' },
          ]"
          type="plain"
        />
      </template>
      <el-scrollbar v-if="active === '1'">
        <div>
          <el-descriptions title="" :column="4">
            <el-descriptions-item :width="100" label="出库通知单">
              <ele-copyable>{{ info.order_sn }}</ele-copyable>
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="来源单号">
              <ele-copyable v-if="info.source_order_sn">{{ info.source_order_sn }}</ele-copyable>
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="货主">
              {{ info.supplier_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="发货仓库">
              {{ info.warehouse_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="业务类型">
              <el-tag v-if="info.type_name" :type="getType(info.type)">
                {{ info.type_name }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="订单状态">
              <el-tag v-if="info.status_name" :type="getType(info.status)">
                {{ info.status_name }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="品数">
              {{ info.product_num || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="商品总数">
              {{ info.num || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="收货人">
              {{ info.contacts || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="联系电话">
              {{ info.phone || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :span="2" label="联系地址">
              {{ info.address || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="创建人">
              {{ info.create_user_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="创建时间">
              {{ info.create_time ? formatDate(info.create_time) : '-' }}
            </el-descriptions-item>

            <el-descriptions-item :span="2" label="备注">
              {{ info.remark || '-' }}
            </el-descriptions-item>
          </el-descriptions>

          <el-descriptions class="mt-20px" title="商品信息" :column="1" />

          <el-form ref="formRef" label-suffix="" class="overflow-hidden" :model="{ product }" :rules="rules" label-width="auto">
            <el-form-item label="" label-position="top" label-width="200px" prop="product">
              <el-table
                :data="product"
                border
                style="width: 100%"
                show-summary
                :summary-method="getSummaries"
                class="form-table"
                row-key="product_id"
              >
                <el-table-column type="index" label="序" width="60" align="center" />
                <el-table-column prop="product_name" label="商品名称" align="left" min-width="130" />
                <el-table-column prop="product_code" label="商品编码" align="center" />
                <el-table-column prop="unit" label="单位" align="center" />

                <el-table-column prop="unit_list" label="单位转换" align="center" min-width="100">
                  <template #default="{ row }">
                    <div class="flex-wrap flex-ca text-#555">
                      <div v-for="(item, i) in formatUnitList(row.unit_list)" :key="i" class=""><span v-if="i" class="mx-3px">=</span>{{ item.ratio_num }}{{ item.unit }}</div>
                      <div v-if="!formatUnitList(row.unit_list).length">-</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="num" label="商品数量" align="center" />
                <el-table-column prop="pick_num" label="拣货数量" align="center" />
                <template v-if="command === 'JH'">
                  <el-table-column prop="post_num" label="本次拣货数量" align="center" :width="160">
                    <template #default="{ row, $index }">
                      <div class="flex-c">
                        <el-form-item
                          :label-width="0"
                          :prop="`product[${$index}].post_num`"
                          required
                        >
                          <el-input
                            v-model="row.post_num"
                            class="w-100px!"
                            placeholder="数量"
                            oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                          >
                            <!-- @blur="row.post_num = checkMax(row)" -->
                            <template #suffix><span class="text-#333!">{{ row.unit }}</span></template>
                          </el-input>
                        </el-form-item>
                      </div>
                    </template>
                  </el-table-column>

                  <el-table-column prop="location" label="库位" align="center" :width="160">
                    <template #default="{ row, $index }">
                      <div class="flex-c">
                        <el-form-item
                          :label-width="0"
                          :prop="`product[${$index}].location_id`"
                          :required="row.post_num > 0"
                        >
                          <el-select
                            v-model="row.location_id"
                            filterable
                            clearable
                            placeholder="请选择库位"
                          >
                            <el-option
                              v-for="item in row.location"
                              :key="item.id"
                              :value="item.id"
                              :label="item.name"
                            />
                          </el-select>
                        </el-form-item>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column :formatter="row => row.location?.find?.(v => v.id === row.location_id)?.stock ?? '-'" prop="stock" label="库存" align="center" />
                </template>
                <el-table-column prop="inspect_num" label="验货数量" align="center" />
                <el-table-column prop="pack_num" label="打包数量" align="center" />
                <el-table-column v-if="command === 'DB'" prop="post_num" label="本次打包数量" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :label-width="0"
                      :prop="`product[${$index}].post_num`"
                      required
                    >
                      <el-input
                        v-model="row.post_num"
                        class="w-100px!"
                        placeholder="数量"
                        oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                        @blur="row.post_num = checkMax(row)"
                      >
                        <template #suffix><span class="text-#333!">{{ row.unit }}</span></template>
                      </el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="out_num" label="发货数量" align="center" />
              </el-table>
            </el-form-item>
          </el-form>
        </div>
      </el-scrollbar>
      <PickList v-if="active === '2'" :orderId="info.id" @done="getInfo" />
      <InspectList v-if="active === '3'" :isDb="info.is_db === 1" :orderId="info.id" @onDb="onDb" @done="getInfo" />
      <PackList v-if="active === '4'" :orderId="info.id" :orderSn="info.order_sn" @done="getInfo" />
      <DeliveryList v-if="active === '5'" :orderId="info.id" @done="getInfo" />
      <Operation v-if="active === '6'" :orderId="info.id" @done="getInfo" />
    </ele-card>

    <PagePrint v-model="showPrint" :objId="info.order_sn" />
  </ele-page>
</template>

<script setup>
import PagePrint from '../components/print.vue'
import DeliveryList from './components/delivery-list.vue'
import InspectList from './components/inspect-list.vue'
// 拣货要取出库单详情商品，验货取拣货单商品，打包取出库单详情商品
import Operation from './components/operation.vue'
import PackList from './components/pack-list.vue'

import PickList from './components/pick-list.vue'

defineOptions({ name: 'OutboundNoticeInfo' })

const orderId = ref(0)
const route = useRoute()
const router = useRouter()
const { routeTabKey, removePageTab, setPageTabTitle } = utils.usePageTab()
const { formatDate, getType } = utils
const info = ref({ product_list: [] })
const active = ref('1')

const formRef = ref(null)

const rules = reactive({})

const loading = ref(false)

const command = ref('')

const product = ref([])

const showPrint = ref(false)
function openPrint() {
  showPrint.value = true
}

onMounted(() => {
  orderId.value = route.params?.id
  getInfo()
})

function goBack() {
  removePageTab({ key: routeTabKey })
  router.push('/outbound/notice')
}

function onDb() {
  active.value = '1'
  onCommand('DB')
}

function checkMax(row) {
  return utils.Big(row.post_num).gt(row.max) ? row.max : row.post_num
}

function back() {
  command.value = ''
  product.value = info.value.product_list
}

function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true

    const formData = { }
    let url = ''

    // /outboundPick/batchRecord
    if (command.value === 'JH') {
      formData.outbound_id = info.value.id
      formData.pick_list = product.value.filter(v => v.post_num > 0).map(v => ({
        outbound_product_id: v.id,
        location_id: v.location_id,
        num: v.post_num,
      }))
      url = '/outboundPick/batchRecord'
    }
    else if (command.value === 'DB') {
      formData.pack_list = product.value.filter(v => v.post_num > 0).map(v => ({
        product_id: v.product_id,
        num: v.post_num,
      }))
      formData.outbound_order_sn = info.value.order_sn
      url = '/outboundPack/record'
    }

    utils.post(url, formData)
      .then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          getInfo()
        }
      })
      .finally(() => {
        loading.value = false
      })
  })
}

async function onCommand(value) {
  value = value.toUpperCase()
  if (value === 'START') {
    utils.confirm('是否确定开始拣货', '提示').then(() => {
      utils.post('/outboundPick/start', { outbound_id: info.value.id }).then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          getInfo()
        }
      })
    })
  }

  else if (value === 'JD') {
    const opts = {
      type: 'warning',
      dangerouslyUseHTMLString: true,
    }
    utils.confirm(`确定要<span class="px-2px text-danger font-semibold">结单</span>订单吗`, '系统提示', opts).then(() => {
      const Loading = utils.message('请求中..', 'loading')
      utils.post('/outbound/jd', { id: info.value.id }).then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          getInfo()
        }
      }).finally(() => {
        Loading.close()
      })
    })
  }

  else if (value === 'JH') {
    const productList = info.value.product_list.filter((v) => {
      const max = utils.Big(v.num).minus(v.pick_num).toNumber()
      v.max = max > 0 ? max : 0
      return max > 0
    })
    const productIds = productList.map(v => v.product_id)

    const res = await utils.get('/warehouseLocation/product', {
      product_ids: productIds.toString(),
      warehouse_id: info.value.warehouse_id,
      is_stock: 1,
    })

    product.value = productList.map((v) => {
      const find = res.data.find(d => Number(d.product_id) === Number(v.product_id))
      find.location = find?.location ?? []
      if (find.location.length) {
        find.location.sort((a, b) => a.type - b.type)
      }
      v.location = find.location
      v.stock = find?.stock ?? 0
      v.post_num = ''
      v.location_id = find.location.length ? find.location[0].id : ''
      return v
    })
    command.value = value
  }
  else if (value === 'DB') {
    product.value = info.value.product_list.filter((v) => {
      const max = utils.Big(v.inspect_num).minus(v.pack_num).toNumber()
      v.post_num = ''
      v.max = max > 0 ? max : 0
      return max > 0
    })
    command.value = value
  }
  else if (value === 'YH') {
    active.value = '2'
  }
  else if (value === 'FH') {
    active.value = '4'
  }
  else if (value === 'CD') {
    const opts = {
      type: 'warning',
      dangerouslyUseHTMLString: true,
      cancelButtonText: '不取消了',
      confirmButtonText: '确定取消',
    }
    utils.confirm(`确定要<span class="px-2px text-danger font-semibold">取消</span>订单吗`, '系统提示', opts).then(() => {
      const Loading = utils.message('请求中..', 'loading')
      utils.post('/outbound/cancel', { id: [info.value.id] }).then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          getInfo()
        }
      }).finally(() => {
        Loading.close()
      })
    })
  }
}

function getInfo() {
  utils.get('/outbound/info', { outbound_order_sn: orderId.value }).then((res) => {
    info.value = res.data
    product.value = res.data.product_list
    command.value = ''
    setPageTabTitle(`出库通知单[${utils.ellipsisStr(res.data.order_sn, 0, 10)}]`)
  })
}

function formatUnitList(data = []) {
  if (data?.length < 2)
    return []

  data.sort((a, b) => a.ratio - b.ratio)
  const ratio = data[data.length - 1].ratio
  data.forEach((v) => {
    v.ratio_num = utils.Big(ratio).div(v.ratio).round(4).valueOf()
  })
  return data
}

function getSummaries({ columns, data }) {
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const keys = ['num', 'out_num', 'pick_num', 'inspect_num', 'pack_num', 'post_num']
    if (keys.includes(column.property)) {
      sums[index] = data.reduce((acc, cur) => {
        const num = column.property === 'num' ? cur[column.property] : cur[column.property]
        return utils.Big(acc).plus(num).valueOf()
      }, 0)
    }
    else {
      sums[index] = ''
    }
  })

  return sums
}
</script>

<style lang="scss" scoped></style>
